package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * 227. 基本计算器 II
 * 面试题 16.26. 计算器
 *
 * @Author liw
 * @Date 2021/5/8 12:49
 * @Version 1.0
 */
public class Calculate {
    public int calculate(String s) {
        s = s + "+";
        char op = '+';
        Stack<Integer> stack = new Stack<>();
        // 保存当前数字，如：12是两个字符，需要进位累加
        int num = 0;
        int result = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c >= '0') {
                num = num * 10 - '0' + c;
            } else if  ((c != ' ') || i == length - 1) {
                switch (op) {
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        stack.push(stack.pop() * num);
                        break;
                    case '/':
                        stack.push(stack.pop() / num);
                        break;
                }
                op = c;
                num = 0;
            }
        }
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }

}
